
try:
    import cx_Oracle
except:
    cx_Oracle = None
from .base import ComponentBase
from .dbapi import SQLConnectionImpl

class OracleConnection(SQLConnectionImpl, ComponentBase):
    def __init__(self, sid, uid=None, pwd=None):
        ComponentBase.__init__(self)
        self.sid = sid
        self.uid = uid
        self.pwd = pwd

    def openImpl(self):
        if self.uid != None:
          cs = '%s'%self.uid
        if self.pwd != None:
          cs += '/%s'%self.pwd
        cs += '@%s'%self.sid
        self.setConnection(cx_Oracle.connect(cs))

    def closeImpl(self):
        self.getConnection().commit()
        self.getConnection().close()
        
    def makeInsert(self, table, fields):
        sql_list = ["insert into ", table, "("]
        field_list = []
        value_list = []
        is_first = True
        i=1
        for field in fields:
            if is_first:
                is_first = False
            else:
                field_list.append(", ")
                value_list.append(", ")
            field_list.append(field)
            value_list.extend([":"+str(i)])
            i+=1
        sql_list.extend(field_list)
        sql_list.append(") values(")
        sql_list.extend(value_list)
        sql_list.append(")")
        return "".join(sql_list)